/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model2;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import javax.swing.text.html.HTMLEditorKit.ParserCallback;
import javax.swing.text.html.parser.ParserDelegator;

/**
 *
 * @author Dustin
 */
public class Parser {

    private List<URL> links;
    private List<URL> images;
    private URL url;
    private URI uri;

    public Parser(byte[] content, URL anURL) throws IOException {
        System.out.println("PRS: Begin of parsing for URL:" + anURL);
        links = new ArrayList<URL>();
        images = new ArrayList<URL>();
        url = anURL;
        try {
            uri = anURL.toURI();
        } catch (URISyntaxException ex) {
            ex.printStackTrace();
        }

        Reader r = new StringReader(new String(content));

        new ParserDelegator().parse(r, new CallbackHandler(), true);
        System.out.println("PRS: End of parsing for URL:" + anURL);
    }

    public List<URL> getLinks() {
        return links;
    }

    public List<URL> getImages() {
        return images;
    }

    private class CallbackHandler extends ParserCallback {

        @Override
        public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
            if (t == Tag.A) {
                try {
                    URI blauri = new URI(a.getAttribute(Attribute.HREF).toString());
                    if (!blauri.isAbsolute()) {
                        URI nuri = uri.resolve(blauri);
                        blauri = nuri;
                    }
                    URL urlletje = blauri.toURL();
                    links.add(urlletje);
                } catch (Exception ex) {
                    System.err.println("Skipping nonparsable url: " + a.getAttribute(Attribute.HREF).toString());
                }
            }
        }

        @Override
        public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
            if (t == Tag.IMG) {
                try {
                    URI blauri = new URI(a.getAttribute(Attribute.SRC).toString());
                    if (!blauri.isAbsolute()) {
                        URI nuri = uri.resolve(blauri);
                        blauri = nuri;
                    }
                    URL urlletje = blauri.toURL();
                    images.add(urlletje);
                } catch (Exception ex) {
                    System.err.println("Skipping nonparsable url: " + a.getAttribute(Attribute.HREF).toString());
                }
            }
        }
    }
}
